//
//  ZBPickerView.m
//  ZBTechniqueLibrary
//
//  Created by apple on 2018/9/30.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "ZBPickerView.h"

#define ZBPickerView_SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define ZBPickerView_SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#define ZBPickerView_header_LINE 0.5

#define ZBPickerView_Duration  0.25

static const NSInteger KProvinceComponent = 0;
static const NSInteger KCityComponent = 1;
static const NSInteger KDistrictComponent = 2;

@interface ZBPickerView()<UIPickerViewDelegate,UIPickerViewDataSource>


@property (nonatomic, strong) UIView *container;
//header控件
@property (nonatomic, strong) UIView *header;
@property (nonatomic, strong) UIButton *cancleButton;
@property (nonatomic, strong) UIButton *ensureButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIView *headerLine;

//选择控件
@property (nonatomic, strong) UIPickerView *datePickerView;
@property (nonatomic, strong) UIDatePicker *datePicker;

//data
@property (nonatomic, strong)  ZBPickerConfig *config;

@property (nonatomic, assign) ZBPickerValueType currentType;

@property (nonatomic, copy) selectBlock compeletionBlock;

@property (nonatomic, assign) NSInteger selectRow,selectIndex;
@property (nonatomic, assign) NSInteger selectProvince,selectCity,selectDistrict;

@property (nonatomic, strong)  NSMutableArray  *dataList;

@property (nonatomic, copy) NSString *dateSelectString;
@property (nonatomic, strong) NSArray *provinList,*cityList,*districtList;

@end

@implementation ZBPickerView
+ (void)showPickerViewDefaultConfigWithType:(ZBPickerValueType)type compeletion:(selectBlock)compeletion
{
    [self showPickerViewWithconfig:[ZBPickerConfig defaultPickerConfig] type:type compeletion:compeletion];
}

+ (void)showPickerViewWithconfig:(ZBPickerConfig *)config type:(ZBPickerValueType)type compeletion:(selectBlock)compeletion
{
    [self showPickerViewWithInView:nil config:config  type:type compeletion:compeletion];
}

+ (void)showPickerViewWithInView:(UIView *)superView config:(ZBPickerConfig *)config type:(ZBPickerValueType)type compeletion:(selectBlock)compeletion
{
    if(superView == nil){
        superView = [UIApplication sharedApplication].keyWindow;
    }
    ZBPickerView *pickerView = [[ZBPickerView alloc]initWithConfig:config];
    pickerView.frame = [UIScreen mainScreen].bounds;
    pickerView.currentType = type;
    pickerView.compeletionBlock = compeletion;
     [superView addSubview:pickerView];
    
    [pickerView showAnimation];
    
    
    
}

//显示pickerView
- (void)showPickerViewWithDidSelect:(selectBlock)compeletion
{
    [self showPickerViewInView:nil handledidSelect:compeletion];
}

- (void)showPickerViewInView:(UIView *)superView handledidSelect:(selectBlock)compeletion
{
    if(superView == nil){
        superView = [UIApplication sharedApplication].keyWindow;
    }
    self.frame = [UIScreen mainScreen].bounds;
    [superView addSubview:self];
    
    self.compeletionBlock = compeletion;
    [self showAnimation];
}





#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    NSInteger count = 1;
  
    switch (self.currentType) {
        case ZBPickerValueType_sex:
        {
            count = 1;
        }
            break;
        case ZBPickerValueType_city:
        {
            count = 3;
        }
          break;
        default:
            {
                if([self.dataSouce respondsToSelector:@selector(zb_numberOfComponentsInPickerView:)]){
                    count = [self.dataSouce zb_numberOfComponentsInPickerView:self];
                }
            }
            break;
    }
    return count;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSInteger count = 0;
    switch (self.currentType) {
        case ZBPickerValueType_sex:
            {
                count = self.dataList.count;
            }
            break;
        case ZBPickerValueType_city:
            {
                if (component == KProvinceComponent) {
                    count = self.provinList.count;
                }else if (component == KCityComponent) {
                    count = self.cityList.count;
                }else {
                     count = self.districtList.count;
                }
            }
            break;
            
        default:
            {
                if([self.dataSouce respondsToSelector:@selector(zb_pickerView:numberOfRowsInComponent:)]){
                    count = [self.dataSouce zb_pickerView:self numberOfRowsInComponent:component];
                }
            }
            break;
    }
    
    return count;
}
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *title = @"";
    switch (self.currentType) {
        case ZBPickerValueType_sex:
        {
            if(row < self.dataList.count){
                title = self.dataList[row];
            }
        }
            break;
        case ZBPickerValueType_city:
        {
            if (component == KProvinceComponent) {
                if(row < self.provinList.count){
                    ZBAddressModel *provinceModel = self.provinList[row];
                    title = provinceModel.name;
                }
            }else if (component == KCityComponent) {
                if(row < self.cityList.count){
                    ZBAddressModel *cityModel = self.cityList[row];
                    title = cityModel.name;
                }
                
            }else {
                if(row < self.districtList.count){
                    ZBAddressModel *districtModel = self.districtList[row];
                    title = districtModel.name;
                }
            }
        }
            break;
        default:
        {
            if([self.dataSouce respondsToSelector:@selector(zb_pickerView:titleForRow:forComponent:)]){
                title = [self.dataSouce zb_pickerView:self titleForRow:row forComponent:component];
            }
        }
            break;
    }
    
    return title;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (self.currentType) {
        case ZBPickerValueType_city:
            {
                if(component == KProvinceComponent){
                    [self computeProvinceIndex:row cityIndex:0];
                    [pickerView selectRow:0 inComponent:KCityComponent animated:YES];
                    [pickerView selectRow:0 inComponent:KDistrictComponent animated:YES];
                    [pickerView reloadComponent:KCityComponent];
                    [pickerView reloadComponent:KDistrictComponent];
                }else if (component == KCityComponent){
                    NSInteger provinceIndex = [pickerView selectedRowInComponent:KProvinceComponent];
                    [self computeProvinceIndex:provinceIndex cityIndex:row];
                    [pickerView selectRow:0 inComponent:KDistrictComponent animated:YES];
                    [pickerView reloadComponent:KDistrictComponent];
                }
                self.selectProvince = [pickerView selectedRowInComponent:KProvinceComponent];
                self.selectCity = [pickerView selectedRowInComponent:KCityComponent];
                self.selectDistrict = [pickerView selectedRowInComponent:KDistrictComponent];
            }
            break;
            
        default:
            {
                if([self.delegate respondsToSelector:@selector(zb_pickerView:didSelectRow:inComponent:)]){
                    [self.delegate zb_pickerView:self didSelectRow:row inComponent:component];
                }
                self.selectRow = row;
                self.selectIndex = component;
            }
            break;
    }
    
}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return self.config.rowHeight;
}



#pragma mark - pravite

- (instancetype)initWithConfig:(ZBPickerConfig *)config
{
    self.config = config;
    if(self = [self init])
    {
        
    }
    return self;
}
- (instancetype)init
{
    if(self = [super init])
    {
        if(self.config == nil){
            self.config = [ZBPickerConfig defaultPickerConfig];
        }
        [self addSubview:self.container];
        [self.container addSubview:self.datePickerView];
        [self.container addSubview:self.datePicker];
        [self.container addSubview:self.header];
        [self.header addSubview:self.cancleButton];
        [self.header addSubview:self.ensureButton];
        [self.header addSubview:self.titleLabel];
        [self.header addSubview:self.headerLine];
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
        
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackgroundEvent)]];
        
        self.currentType = ZBPickerValueType_None;
        self.selectRow = 0;
        self.selectIndex = 0;
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat allHeight = self.config.headerHeight + self.config.pickerViewHeight;
    
    //布局
    self.container.frame = CGRectMake(0, ZBPickerView_SCREEN_HEIGHT, ZBPickerView_SCREEN_WIDTH, allHeight);
    
    //header
    self.header.frame = CGRectMake(0, 0, self.container.frame.size.width, self.config.headerHeight);
    
    self.headerLine.frame = CGRectMake(0, self.header.bounds.size.height - ZBPickerView_header_LINE, self.header.bounds.size.width,ZBPickerView_header_LINE);
    
    CGFloat margin = 5;
    CGFloat cancleButtonX = margin;
    CGFloat cancleButtonY = 0;
    CGFloat cancleButtonW = ceil([self.config.cancleTitle sizeWithAttributes:@{NSFontAttributeName : self.config.cancleFont}].width);
    CGFloat cancleButtonH = self.header.bounds.size.height - ZBPickerView_header_LINE;
    self.cancleButton.frame = CGRectMake(cancleButtonX, cancleButtonY, cancleButtonW, cancleButtonH);
    
    CGFloat ensureButtonW = ceil([self.config.ensureTitle sizeWithAttributes:@{NSFontAttributeName : self.config.ensureFont}].width);
    CGFloat ensureButtonH = cancleButtonH;
    
    CGFloat ensureButtonX = self.header.bounds.size.width - ensureButtonW - 2*margin;
    CGFloat ensureButtonY = cancleButtonY;
    
    self.ensureButton.frame = CGRectMake(ensureButtonX, ensureButtonY, ensureButtonW, ensureButtonH);
    
    
    CGFloat titleLabelW = self.header.bounds.size.width - ensureButtonW - cancleButtonW - 4*margin;
    CGFloat titleLabelH = cancleButtonH;
    
    CGFloat titleLabelX = CGRectGetMaxX(self.cancleButton.frame) + margin;
    CGFloat titleLabelY = cancleButtonY;
    
    self.titleLabel.frame = CGRectMake(titleLabelX, titleLabelY, titleLabelW, titleLabelH);
    

    //picker
    self.datePickerView.frame = CGRectMake(0, CGRectGetMaxY(self.header.frame), self.container.frame.size.width, self.container.bounds.size.height - self.header.bounds.size.height);
    
    self.datePicker.frame = CGRectMake(0, CGRectGetMaxY(self.header.frame), self.container.frame.size.width, self.container.bounds.size.height - self.header.bounds.size.height);
}

- (void)setConfig:(ZBPickerConfig *)config
{
    _config = config;
    
    self.header.backgroundColor = config.headerBackgroundColor;
    self.headerLine.backgroundColor = config.headerLineBackgroundColor;
    self.headerLine.hidden = config.headerBottomLineHidden;
    
    self.cancleButton.titleLabel.font = config.cancleFont;
    [self.cancleButton setTitle:config.cancleTitle forState:UIControlStateNormal];
    [self.cancleButton setTitleColor:config.cancleColor forState:UIControlStateNormal];
    
    self.ensureButton.titleLabel.font = config.ensureFont;
    [self.ensureButton setTitle:config.ensureTitle forState:UIControlStateNormal];
    [self.ensureButton setTitleColor:config.ensureColor forState:UIControlStateNormal];
    
    self.titleLabel.font = config.textFont;
    self.titleLabel.text = config.textTitle;
    self.titleLabel.textColor = config.textColor;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    
}

- (void)setCurrentType:(ZBPickerValueType)currentType
{
    _currentType = currentType;
    self.datePickerView.hidden = NO;
    self.datePicker.hidden = YES;
    if(currentType == ZBPickerValueType_None) return;
    [self.dataList removeAllObjects];
    switch (currentType) {
        case ZBPickerValueType_sex:
            {
                self.titleLabel.text = @"选择性别";
                [self.dataList addObjectsFromArray:@[@"男",@"女"]];
            }
            break;
        case ZBPickerValueType_yyyymmdd:
            {
                self.titleLabel.text = @"选择年月日";
                self.datePickerView.hidden = YES;
                self.datePicker.hidden = NO;
                self.datePicker.datePickerMode = UIDatePickerModeDate;
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                //设置时间格式
                formatter.dateFormat = self.config.dateFormat;
                NSString *dateStr = [formatter  stringFromDate:[NSDate date]];
                self.dateSelectString = dateStr;
                if(self.config.minDate != nil){
                   [self.datePicker setMinimumDate:self.config.minDate];
                }
                if(self.config.maxDate != nil){
                   [self.datePicker setMaximumDate:self.config.maxDate];
                }
                
            }
            break;
        case ZBPickerValueType_hhmmss:
            {
                self.titleLabel.text = @"选择时间";
                self.datePickerView.hidden = YES;
                self.datePicker.hidden = NO;
                self.datePicker.datePickerMode = UIDatePickerModeTime;
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                //设置时间格式
                formatter.dateFormat = self.config.timeFormat;
                NSString *dateStr = [formatter  stringFromDate:[NSDate date]];
                self.dateSelectString = dateStr;
            }
            break;
        case ZBPickerValueType_city:
            {
               self.titleLabel.text = @"城市选择";
                NSBundle *bundle = [NSBundle mainBundle];
                NSString *plistPath = [bundle pathForResource:@"ZBAddrssList" ofType:@"plist"];
                NSArray *dictArray = [[NSArray alloc] initWithContentsOfFile:plistPath];
                NSMutableArray *appArray = [NSMutableArray array];
                for (NSDictionary *dict in dictArray) {
                   
                    ZBAddressModel *app = [[ZBAddressModel alloc]initWithDict:dict];
                    
                    [appArray addObject:app];
                }
                self.dataList = appArray;
                self.selectProvince = 0;
                self.selectDistrict = 0;
                self.selectCity = 0;
                self.provinList = self.dataList;
                [self computeProvinceIndex:self.selectProvince cityIndex:self.selectCity];
                
            }
            break;
            
        default:
            break;
    }
}


#pragma mark - 地址处理
- (void)computeProvinceIndex:(NSInteger)provinceIndex cityIndex:(NSInteger)cityIndex
{
    if(provinceIndex < self.provinList.count){
       ZBAddressModel *provinceModel = self.provinList[provinceIndex];
        self.cityList = provinceModel.list;
        
        if(cityIndex < self.cityList.count){
            ZBAddressModel *cityModel = self.cityList[cityIndex];
            self.districtList = cityModel.list;
        }
    }
}



#pragma mark - 事件
//显示动画
- (void)showAnimation
{
    [UIView animateWithDuration:ZBPickerView_Duration animations:^{
        self.alpha = 1.0;
    }completion:^(BOOL finished) {
        [UIView animateWithDuration:ZBPickerView_Duration animations:^{
            CGRect frame = self.container.frame;
            frame.origin.y = ZBPickerView_SCREEN_HEIGHT - self.container.frame.size.height;
            self.container.frame = frame;
        }];
        
    }];
}

//隐藏动画
- (void)dismissAnimation
{
    [UIView animateWithDuration:ZBPickerView_Duration animations:^{
        CGRect frame = self.container.frame;
        frame.origin.y = ZBPickerView_SCREEN_HEIGHT;
        self.container.frame = frame;
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.0];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)tapBackgroundEvent
{
    [self dismissAnimation];
}
- (void)ensureButtonTargetEvent
{
    [self dismissAnimation];
    NSString *selectString = @"";
    switch (self.currentType) {
        case ZBPickerValueType_sex:
            {
                if(self.selectRow < self.dataList.count){
                    selectString = self.dataList[self.selectRow];
                }
            }
            break;
        case ZBPickerValueType_hhmmss:
        case ZBPickerValueType_yyyymmdd:
            {
                selectString = self.dateSelectString;
            }
            break;
        case ZBPickerValueType_city:
            {
                NSString *address = @"";
                if(self.selectProvince < self.provinList.count){
                    ZBAddressModel *province = self.provinList[self.selectProvince];
                    address =[address stringByAppendingFormat:@"%@",province.name];
                }
                if(self.selectCity < self.cityList.count){
                    ZBAddressModel *city = self.cityList[self.selectCity];
                    address =[address stringByAppendingFormat:@" %@",city.name];
                }
                if(self.selectDistrict < self.districtList.count){
                    ZBAddressModel *district = self.districtList[self.selectDistrict];
                    address =[address stringByAppendingFormat:@" %@",district.name];
                }
                selectString = address;
            }
        
            break;
            
        default:
            {
                if([self.dataSouce respondsToSelector:@selector(zb_pickerView:titleForRow:forComponent:)]){
                    selectString = [self.dataSouce zb_pickerView:self titleForRow:self.selectRow forComponent:self.selectIndex];
                }
            }
            break;
    }
    if(self.compeletionBlock)
        self.compeletionBlock(self.selectRow, self.selectIndex,selectString);
}

- (void)datePickerChangeEvent:(UIDatePicker *)datePicker
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //设置时间格式
    if(datePicker.datePickerMode == UIDatePickerModeTime){
        [formatter setDateFormat:self.config.timeFormat];
        NSString *resultString=[formatter stringFromDate:datePicker.date];
        self.dateSelectString = resultString;
    }else{
        formatter.dateFormat = self.config.dateFormat;
        NSString *dateStr = [formatter  stringFromDate:datePicker.date];
        self.dateSelectString = dateStr;
    }
    
    
  
    
    
}


#pragma mark - lazy
- (UIView *)container
{
    if(_container == nil)
    {
        _container = [UIView new];
    }
    return _container;
}
- (UIView *)header
{
    if(_header == nil)
    {
        _header = [UIView new];
    }
    return _header;
}
- (UIButton *)cancleButton
{
    if(_cancleButton == nil)
    {
        _cancleButton =  [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancleButton addTarget:self action:@selector(dismissAnimation) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancleButton;
}
- (UIButton *)ensureButton
{
    if(_ensureButton == nil)
    {
        _ensureButton =  [UIButton buttonWithType:UIButtonTypeCustom];
        [_ensureButton addTarget:self action:@selector(ensureButtonTargetEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    return _ensureButton;
}
- (UILabel *)titleLabel
{
    if(_titleLabel == nil)
    {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}
- (UIView *)headerLine
{
    if(_headerLine == nil)
    {
        _headerLine = [UIView new];
    }
    return _headerLine;
}

- (UIDatePicker *)datePicker
{
    if(_datePicker == nil)
    {
        _datePicker = [[UIDatePicker alloc]init];
        _datePicker.backgroundColor = [UIColor whiteColor];
        //设置地区: zh-中国
        _datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
        // 设置当前显示时间
        [_datePicker setDate:[NSDate date] animated:YES];
        //监听DataPicker的滚动
        [_datePicker addTarget:self action:@selector(datePickerChangeEvent:) forControlEvents:UIControlEventValueChanged];
    }
    return _datePicker;
}
- (UIPickerView *)datePickerView
{
    if(_datePickerView == nil)
    {
        _datePickerView = [[UIPickerView alloc]init];
        _datePickerView.dataSource = self;
        _datePickerView.delegate = self;
        _datePickerView.backgroundColor = [UIColor whiteColor];
    }
    return _datePickerView;
}

- (NSMutableArray *)dataList
{
    if(_dataList == nil)
    {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

@end
